import numpy as np

def improved_build_interpolated_topology(node_list, max_interpolation_distance=5.0):
    """
    改进的完整插值网络构建（修复连接问题）
    """
    all_nodes = {node['node_name']: node for node in node_list}
    new_topology = []
    processed_edges = set()  # 避免重复处理
    
    # 添加原始节点
    for node in node_list:
        new_topology.append(node.copy())
    
    # 处理每条边只一次
    for node_name, node in all_nodes.items():
        neighbors_str = node['param'][4]
        neighbors = [n.strip() for n in neighbors_str.split(',')]
        
        for neighbor_name in neighbors:
            if neighbor_name in all_nodes:
                # 确保每条边只处理一次 (f1-f2 和 f2-f1 只处理一次)
                edge_key = tuple(sorted([node_name, neighbor_name]))
                if edge_key in processed_edges:
                    continue
                processed_edges.add(edge_key)
                
                print(f"处理边: {node_name} - {neighbor_name}")
                
                # 创建插值点
                start_pos = np.array(node['param'][:2])
                end_pos = np.array(all_nodes[neighbor_name]['param'][:2])
                
                distance = np.linalg.norm(end_pos - start_pos)
                num_interpolated = int(distance / max_interpolation_distance)
                
                # 存储创建的插值点名称，用于建立相邻连接
                created_interpolated_nodes = []
                
                if num_interpolated > 0:
                    for i in range(1, num_interpolated + 1):
                        ratio = i / (num_interpolated + 1)
                        pos = start_pos + ratio * (end_pos - start_pos)
                        
                        interpolated_name = f"int_{node_name}_{neighbor_name}_{i}"
                        created_interpolated_nodes.append(interpolated_name)
                        
                        # 确定当前插值点的邻居
                        neighbors_list = []
                        
                        # 连接到前一个插值点（如果存在）
                        if i > 1:
                            neighbors_list.append(f"int_{node_name}_{neighbor_name}_{i-1}")
                        else:
                            # 如果是第一个插值点，连接到起始节点
                            neighbors_list.append(node_name)
                        
                        # 连接到后一个插值点（如果存在）
                        if i < num_interpolated:
                            neighbors_list.append(f"int_{node_name}_{neighbor_name}_{i+1}")
                        else:
                            # 如果是最后一个插值点，连接到结束节点
                            neighbors_list.append(neighbor_name)
                        
                        interpolated_node = {
                            'node_name': interpolated_name,
                            'floor': node['floor'],
                            'param': [
                                float(pos[0]), float(pos[1]), 0.0, 0.0,
                                ','.join(neighbors_list),  # 正确的邻居连接
                                '1'
                            ]
                        }
                        new_topology.append(interpolated_node)
                        print(f"  创建插值点: {interpolated_name} at ({pos[0]:.2f}, {pos[1]:.2f}), 邻居: {','.join(neighbors_list)}")
                
                # 更新原始节点的邻居信息（添加插值点）
                # 如果有插值点，更新起始节点和结束节点的邻接关系
                if num_interpolated > 0:
                    # 更新起始节点的邻接关系
                    start_node = next(n for n in new_topology if n['node_name'] == node_name)
                    start_neighbors = [n.strip() for n in start_node['param'][4].split(',')]
                    if neighbor_name in start_neighbors:
                        start_neighbors.remove(neighbor_name)  # 移除直接连接
                        start_neighbors.append(created_interpolated_nodes[0])  # 连接到第一个插值点
                    start_node['param'][4] = ','.join(start_neighbors)
                    
                    # 更新结束节点的邻接关系
                    end_node = next(n for n in new_topology if n['node_name'] == neighbor_name)
                    end_neighbors = [n.strip() for n in end_node['param'][4].split(',')]
                    if node_name in end_neighbors:
                        end_neighbors.remove(node_name)  # 移除直接连接
                        end_neighbors.append(created_interpolated_nodes[-1])  # 连接到最后一个插值点
                    end_node['param'][4] = ','.join(end_neighbors)
                    
                    print(f"  更新 {node_name} 邻居: {start_node['param'][4]}")
                    print(f"  更新 {neighbor_name} 邻居: {end_node['param'][4]}")

    return new_topology

# 您的数据
node_list = [
    {
        'node_name': 'f1',
        'floor': 1,
        'param': [0.29, 3.68, 0.0, -0.03, 'f2', '1']
    },
    {
        'node_name': 'f2',
        'floor': 1,
        'param': [9.33, 4.02, 0.0, 1.63, 'f1,f3', '3']
    },
    {
        'node_name': 'f3',
        'floor': 1,
        'param': [9.06, 13.24, 0.0, -3.1, 'f2,f4', '3']
    },
    {
        'node_name': 'f4',
        'floor': 1,
        'param': [-8.13, 13.62, 0.0, 3.14, 'f3', '2']
    }
]

# 运行程序
print("原始节点列表:")
for node in node_list:
    print(f"{node['node_name']}: pos=({node['param'][0]}, {node['param'][1]}), neighbors={node['param'][4]}")

print("\n开始构建插值网络...")
result = improved_build_interpolated_topology(node_list, max_interpolation_distance=5.0)

print(f"\n插值后节点总数: {len(result)}")
print("\n插值后完整网络:")
for node in result:
    print(f"{node['node_name']}: pos=({node['param'][0]}, {node['param'][1]}), neighbors={node['param'][4]}")

print("\n详细连接关系:")
for node in result:
    neighbors = node['param'][4].split(',')
    print(f"{node['node_name']} -> {neighbors}")